#include<iostream>
#include<unistd.h>
#include<sys/timerfd.h>

int main()
{
    int timerfd = ::timerfd_create(CLOCK_MONOTONIC,0);
    if(timerfd < 0)
    {
        std::cerr<<"创建定时器异常！"<<std::endl;
        return -1;
    }
    struct itimerspec new_settimer;
    new_settimer.it_interval.tv_sec = 1;
    new_settimer.it_interval.tv_nsec = 0;
    //设置第一次超时时间
    new_settimer.it_value.tv_sec = 1;
    new_settimer.it_value.tv_nsec = 0;
    int ret = timerfd_settime(timerfd,0,&new_settimer,nullptr);
    if(ret < 0)
    {
        std::cerr<<"设置超时时间异常!"<<std::endl;
        return -2;
    }

    //读取数据
    while(true)
    {
        uint64_t val = 0;
        // sleep(3);测试超时次数
        ssize_t n = ::read(timerfd,&val,sizeof(val));
        if(n < 0)
        {
            std::cerr<<"本次读取定时器异常!"<<std::endl;
            continue;
        }
        std::cout<<"触发超时!,超时次数 = "<<val<<std::endl;
    }
    ::close(timerfd);
    return 0;
}